package com.zym.init.filter;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.UUID;

import static com.zym.init.constant.TraceConstant.TRACE_ID;

/**
 * traceId过滤器
 *
 * @author ZouYangMing
 */
public class TraceFilter extends GenericFilterBean {

    /**
     * 过滤器处理请求和响应
     *
     * @param request  Servlet请求
     * @param response Servlet响应
     * @param chain    过滤器链
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
    }

    /**
     * 执行过滤操作
     *
     * @param request  HTTP请求
     * @param response HTTP响应
     * @param chain    过滤器链
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            String traceId = request.getHeader(TRACE_ID);
            if (StrUtil.isEmpty(traceId)) {
                MDC.put(TRACE_ID, UUID.randomUUID().toString().replace("-", ""));
            } else {
                MDC.put(TRACE_ID, traceId);
            }
            response.addHeader(TRACE_ID, MDC.get(TRACE_ID));
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }
}
